package com.tanhua.manage.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.manage.domain.AnalysisByDay;
import com.tanhua.manage.mapper.AnalysisMapper;
import com.tanhua.manage.mapper.LogMapper;
import com.tanhua.manage.utils.ComputeUtil;
import com.tanhua.manage.vo.AnalysisSummaryVo;
import com.tanhua.manage.vo.LastlastYear;
import com.tanhua.manage.vo.Title;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AnalysisService extends ServiceImpl<AnalysisMapper, AnalysisByDay> {


    @Autowired(required = false)
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;

    /**
     * 统计概要信息
     *
     * @return
     */
    public ResponseEntity<Object> summary() {
        //1. 统计今天数据
        Date now = new Date();
        String nowDate = DateUtil.format(now, "yyyy-MM-dd");
        //1.1 累计用户
        AnalysisByDay analysisByDay = query().select("SUM(`num_registered`) as numRegistered").one();
        Integer cumulativeUsers = analysisByDay.getNumRegistered();

        //1.2 查询今日新增用户, 登陆次数, 活跃用户
        AnalysisByDay analysisByDayToday = query().eq("record_date", nowDate).one();
        Integer numRegisteredToday = 0;
        Integer numLoginToday = 0;
        Integer numActiveToday = 0;
        if (analysisByDayToday != null) {
            numRegisteredToday = analysisByDayToday.getNumRegistered();
        }
        if (analysisByDayToday != null) {
            numLoginToday = analysisByDayToday.getNumLogin();
        }
        if (analysisByDayToday != null) {
            numActiveToday = analysisByDayToday.getNumActive();
        }

        //2. 统计昨天的数据
        Integer numRegisteredYes = 0;
        Integer numLoginYes = 0;
        Integer numActiveYes = 0;
        String yesterday = ComputeUtil.offsetDay(now, -1);
        AnalysisByDay analysisByDayYes = query().eq("record_date", yesterday).one();
        if (analysisByDayYes != null) {
            numRegisteredYes = analysisByDayYes.getNumRegistered();
        }
        if (analysisByDayYes != null) {
            numLoginYes = analysisByDayYes.getNumLogin();
        }
        if (analysisByDayYes != null) {
            numActiveYes = analysisByDayYes.getNumActive();
        }


        //过去7天与30天的活跃用户
        long day7 = this.getBaseMapper().findNumActiveByDate(ComputeUtil.offsetDay(now, -7), nowDate);
        long day30 = this.getBaseMapper().findNumActiveByDate(ComputeUtil.offsetDay(now, -30), nowDate);


        //3. 把数据封装到Vo对象中返回即可
        AnalysisSummaryVo vo = new AnalysisSummaryVo();
        vo.setCumulativeUsers(cumulativeUsers.longValue()); //累计用户
        vo.setActivePassMonth(day30); //过去30天
        vo.setActivePassWeek(day7); //过去7天
        vo.setNewUsersToday(numRegisteredToday.longValue()); //今日新增用户
        vo.setNewUsersTodayRate(ComputeUtil.computeRate(numRegisteredToday, numRegisteredYes)); // 今日新增用户环比率
        vo.setLoginTimesToday(numLoginToday.longValue()); //今日登陆次数
        vo.setLoginTimesTodayRate(ComputeUtil.computeRate(numLoginToday, numLoginYes));
        vo.setActiveUsersToday(numActiveToday.longValue()); //今日活跃用户
        vo.setActiveUsersTodayRate(ComputeUtil.computeRate(numActiveToday, numActiveYes));
        return ResponseEntity.ok(vo);
    }

    //作用分析日志表，把日志表的数据插入到日表中
    public void anasysis() {
        //1. 查看当前日表中有没有今天记录
        String now = DateUtil.formatDate(new Date());//yyyy-MM-dd
        AnalysisByDay analysisByDay = query().eq("record_date", now).one();

        //2. 如果没有今天记录，就插入今天的记录数据，
        if (analysisByDay == null) {
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(new Date());
            analysisByDay.setCreated(new Date());
            analysisByDay.setUpdated(new Date());
            this.save(analysisByDay);
        }
        String yesterday = ComputeUtil.offsetDay(new Date(), -1);
        //3.查询日志表得到 今日注册人数、登陆人数、活跃人数、次日保留人数
        Long loginNum = logMapper.queryNumsByType(now, "0101"); //登陆人数
        Long regNum = logMapper.queryNumsByType(now, "0102"); //登陆人数
        Long activeNum = logMapper.queryNumsByDate(now); //活跃人数
        Long retentNum = logMapper.queryRetention1d(now, yesterday); //登陆人数

        //4. 更新日表的数据
        analysisByDay.setNumRegistered(regNum.intValue());
        analysisByDay.setNumActive(activeNum.intValue());
        analysisByDay.setNumLogin(loginNum.intValue());
        analysisByDay.setNumRetention1d(retentNum.intValue());
        analysisByDay.setUpdated(new Date());
        this.updateById(analysisByDay);
    }


    /**
     * 按天查询
     *
     * @return
     */
    public ResponseEntity<Object> users(Long sd, Long ed, Integer type) {

        //开始时间
        String startTime = DateUtil.date(sd).toString();
        //结束时间
        String endTime = DateUtil.date(ed).toString();

        //上一年的开始时间
        String theStartTimeOfThePreviousYear = DateUtil.date(sd).offset(DateField.YEAR, -1).toString();

        //上一年的结束时间
        String theEndOfThePreviousYear = DateUtil.date(ed).offset(DateField.YEAR, -1).toString();
        String state = null;
        switch (type) {
            case 101:
                state = "num_registered";
                break;
            case 102:
                state = "num_active";
                break;
            case 103:
                state = "num_retention1d";
                break;
        }

        //今年
        List<Title> thisYear = analysisMapper.find(state, startTime, endTime);
        //前一年
        List<Title> theYearBefore = analysisMapper.find(state, theStartTimeOfThePreviousYear, theEndOfThePreviousYear);

        LastlastYear ak = new LastlastYear();
        //今年
        ak.setThisYear(thisYear);
        //去年
        ak.setLastYear(theYearBefore);
        return ResponseEntity.ok(ak);
    }
}
